package com.cmy.utils;

import com.cmy.pojo.User;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

//多线程提升用户体验
public class SendMail extends Thread{
    //给用户发送邮件的邮箱
    private String from = "2603135842@qq.com";
    //邮箱的用户名
    private String username = "2603135842@qq.com";
    //密码(授权码)
    private String password = "cvhfpkpdyrufecic";
    //发送邮件的服务器地址
    private String host = "smtp.qq.com";

    private User user;
    public SendMail(User user){
        this.user = user;
    }


    @Override
    public void run() {

        try {
            Properties properties = new Properties();
            properties.setProperty("mail.host","stmp.qq.com");//设置QQ邮箱服务器
            properties.setProperty("mail.transport.protocol","smtp");
            properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码

            //QQ邮箱需要SSL加密,
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable","true");
            properties.put("mail.smtp.ssl.socketFactory",sf);

//使用JavaMail 发送邮件的5个步骤
            //1.创建定义整个应用程序所需的环境信息的Session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("2603135842@qq.com","cvhfpkpdyrufecic");
                }
            });
            //开启Session的debug模式,以查看程序发送邮件的运行状态
            session.setDebug(true);
            //2.通过session得到transport对象
            Transport ts = session.getTransport();
            //3.使用邮箱的用户名和授权码连上邮件服务器
            ts.connect(host,username,password);
            //4.创建邮件
            //需要传递session
            MimeMessage message = new MimeMessage(session);

            //发件人
            message.setFrom(new InternetAddress(from));
            //收件人
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));
            //邮件主题
            message.setSubject("用户注册邮件");
            //邮件内容
            String info = "恭喜您注册成功!</br>您的用户名:"+user.getUsername() +"</br>您的密码:"+user.getPassword()+"</br>请妥善保存,如有问题请拨打110";
            message.setContent(info,"text/html;charset=UTF-8");
            message.saveChanges();
            //5.发送邮件
            ts.sendMessage(message,message.getAllRecipients());
            //关闭连接
            ts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

    